/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 */
package seedpod.webapp.view.servlet;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seedpod.exceptions.SeedpodException;
import seedpod.model.SeedpodDO;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.webapp.Seedpod;
import seedpod.webapp.view.htmlwidget.CheckBoxInput;
import seedpod.webapp.view.htmlwidget.Table;
import seedpod.webapp.view.htmlwidget.TableRow;


public class InstanceCollection extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	public static String render(HttpServletRequest request, String clsName, Integer limit ) {
		PManager manager = Seedpod.getPManager();
		Table objTable = new Table( );
		TableRow currRow;
		try {
			String filter = (limit == null )? "": " LIMIT " + limit;
			Collection<SeedpodDO> objects = manager.query( clsName, filter );
			Iterator<SeedpodDO> objItr = objects.iterator();
			SeedpodDO obj ;
			while ( objItr.hasNext() ) {
				currRow = objTable.addRow();
				obj = objItr.next(); 
				currRow.addCell( obj.getLabel() );
			}
			return objTable.render();
		}
		catch (SeedpodException e) {
			return e.getMessage();
		}
		
	}
	
	/**
	 * renders a table of objects each with a check box in the front
	 * @param request
	 * @param clsName
	 * @param limit
	 * @return
	 */
	public static String renderSelectionList (String clsName, Integer limit ) {
		PManager manager;
		Table objTable = new Table( );
		TableRow currRow;
		objTable.setCssClass( "boxTable" );
		try {
			manager = PMFactory.getInstance().createManager();
			String filter = (limit == null )? "": " LIMIT " + limit;
			Collection<SeedpodDO> objects = manager.query( clsName, filter );
			
			Iterator<SeedpodDO> objItr = objects.iterator();
			SeedpodDO obj ;
			while ( objItr.hasNext() ) {
				obj = objItr.next(); 
				String cbName = "cb_" + obj.getOid();
				CheckBoxInput cb = new CheckBoxInput( cbName, obj.getOid().toString() );

				currRow = objTable.addRow();
				currRow.addCell( cb );
				currRow.addCell( obj.getLabel() );
			}
			return objTable.render();
		}
		catch (SeedpodException e) {
			return e.getMessage();
		}
		
	}

	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException {
		
	}
	
	public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException {
		
		
	}

	
}
